package com.newcoretech.platform_service

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.newcoretech.platform_service.scanner.thread.QRCodeProcessThread
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.Executors

class NDScannerPlugin {

    private lateinit var mActivity: Activity;
    private lateinit var mViewFactory: AndroidFlutterViewFactory
    private lateinit var pluginBinding: FlutterPlugin.FlutterPluginBinding
    private lateinit var rootPlugin: PlatformServicePlugin
    private lateinit var mPDAMethodChannel: MethodChannel
    private lateinit var mImgMethodChannel: MethodChannel
    private lateinit var mPDAReceiver: PDABroadcastReceiver
    private var pdaEnable = false
    val requestCamera = 7003

    companion object {
        const val TAG: String = "NDScanner2Plugin"
    }

    fun onAttachedToEngine(
        binding: FlutterPlugin.FlutterPluginBinding,
        rootPlugin: PlatformServicePlugin,
    ) {
        Log.d(TAG, "onAttachedToEngine")
        pluginBinding = binding
        this.rootPlugin = rootPlugin
    }

    fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        Log.d(TAG, "onDetachedFromEngine")
    }

    private var activityBinding: ActivityPluginBinding? = null

    fun onAttachedToActivity(
        binding: ActivityPluginBinding,
    ) {
        Log.d(TAG, "onAttachedToActivity")
        val hiddenLifecycle: HiddenLifecycleReference =
            binding.lifecycle as HiddenLifecycleReference
        val lifecycle = hiddenLifecycle.lifecycle
        val messenger = pluginBinding.binaryMessenger
        val methodChannel = MethodChannel(messenger, "scanner")
        mViewFactory = AndroidFlutterViewFactory(binding.activity, methodChannel, lifecycle)
        pluginBinding.platformViewRegistry.registerViewFactory(
            "com.newcore.demo.flutter.plugin/scanner",
            mViewFactory
        )

        activityBinding = binding
        mActivity = binding.activity
        mPDAMethodChannel = MethodChannel(messenger, "com.newcore.demo.flutter.plugin/pda/scanner")
        mPDAMethodChannel.setMethodCallHandler(rootPlugin)

        mImgMethodChannel = MethodChannel(messenger, "com.newcore.demo.flutter.plugin/qrcode/file")
        mImgMethodChannel.setMethodCallHandler(rootPlugin)

        mPDAReceiver = PDABroadcastReceiver(mPDAMethodChannel)
        // checkPermission()
    }

    fun onDetachedFromActivity() {
        Log.d(TAG, "onDetachedFromActivity")
        mPDAMethodChannel.setMethodCallHandler(null)
        if (pdaEnable) mActivity.unregisterReceiver(mPDAReceiver)
        activityBinding = null
    }

    fun onDetachedFromActivityForConfigChanges() {
        onDetachedFromActivity()
    }

    fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        onAttachedToActivity(binding)
    }


    fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "PDAEnable" -> {
                if (pdaEnable) return result.success(true)
                pdaEnable = true
                mActivity.registerReceiver(mPDAReceiver, IntentFilter().apply {
                    addAction(SUNMI_ACTION)
                    addAction(KOZEN_ACTION)
                    addAction(KEYINPUT_PDA_SCAN_ACTION)
                    addAction(JAHT_ACTION)
                    addAction(YD_ACTION)
                    addAction(EDDIE_ZEBRA_ACTION)
                    addAction(NEWCORE_ZEBRA_ACTION)
                    addAction(URONO_ACTION)
                })
                //按键的在MainActivity dispatchKeyEvent控制，发送广播通知
                val keyIntent = Intent("newcore_action_pad_scan")
                keyIntent.putExtra("enable", true)
                LocalBroadcastManager.getInstance(mActivity).sendBroadcast(keyIntent)
                result.success(true)

            }
            "PDADisable" -> {
                if (!pdaEnable) return result.success(true)
                val keyIntent = Intent("newcore_action_pad_scan")
                keyIntent.putExtra("enable", false)
                LocalBroadcastManager.getInstance(mActivity).sendBroadcast(keyIntent)
                result.success(true)
                mActivity.unregisterReceiver(mPDAReceiver)
                pdaEnable = false

            }
            "ScanImage" -> {
                if (call.hasArgument("path")) {
                    val paths = call.argument<List<String>>("path")
                    val service = Executors.newSingleThreadExecutor()
                    result.success(service.submit(QRCodeProcessThread(paths, mActivity)).get())
                    service.shutdown()
                } else {
                    result.success(null)
                }
            }
        }
    }

    fun checkPermission(requestCode: Int, activity: Activity): Boolean {
        return if (ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.READ_PHONE_STATE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                activity,
                arrayOf(
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_PHONE_STATE,
                ),
                requestCode
            )
            false
        } else {
            true
        }
    }

}
